module V1
  class Ads < Grape::API
    before {authenticate!}
    # status 10-删除 1-导入 2-新建

    post 'ad/edit' do
      ad = AdInfo.find_by(id:params[:id])
      sql_p = {}
      sql_p[:eventkey] = params[:eventkey] 
      sql_p[:media_tag] = params[:media_tag]
      sql_p[:media_tag1] = params[:media_tag1]
      sql_p[:media_name] = params[:media_name]
      sql_p[:ad_user_name] = params[:ad_user_name]
      sql_p[:ad_plan] = params[:ad_plan] 
      sql_p[:ad_unit] = params[:ad_unit]
      sql_p[:ad_agent] = params[:ad_agent]
      sql_p[:key_word] = params[:key_word] 
      sql_p[:city_lv] = params[:city_lv] 
      sql_p[:city_name] = params[:city_name] 
      sql_p[:activity_name] = params[:activity_name] 
      sql_p[:product] = params[:product] 
      sql_p[:register_type] = params[:register_type] 
      sql_p[:customer_lv] = params[:customer_lv] 
      sql_p[:customer_type] = params[:customer_type]
      sql_p[:ad_source_name] = params[:ad_source_name] 
      sql_p[:landing_page_url] = params[:landing_page_url] 
      sql_p[:remark] = params[:remark]
      sql_p[:cost] = params[:cost] 

      res_event_key = RestClient::Request.execute(
        method:  "post",
        url:     "#{ENV["crm_host"]}api/channels/generate_tracking",
        payload: {
          :event_key     => params[:eventkey],
          :utm_source    => params[:media_name],
          :utm_medium    => params[:media_tag],
          :utm_campaign  => params[:register_type],
          :grade         => params[:customer_lv]
        },
        headers: { "authorization": ENV["crm_authorization"]})
      event_key_info_code = JSON.parse(res_event_key).fetch("code", nil).to_i

      if event_key_info_code == 200
        ad.update(sql_p)
        render_json JSON.parse(res_event_key)
      else
        error JSON.parse(res_event_key)
      end
    end

    get 'ad/list' do
      sql_p = {}
      sql_p[:created_at] = Time.at(params[:created_at_start].to_i)..Time.at(params[:created_at_end].to_i) if params[:created_at_start].present? && params[:created_at_end].present?
      sql_p[:activity_name] = params[:activity_name] if params[:activity_name].present?
      sql_p[:product] = params[:product] if params[:product].present?
      sql_p[:register_type] = params[:register_type] if params[:register_type].present?
      sql_p[:ad_source_name] = params[:ad_source_name] if params[:ad_source_name].present?
      sql_p[:landing_page_name] = params[:landing_page_name] if params[:landing_page_name].present?
      sql_p[:remark] = params[:remark] if params[:remark].present?
      sql_p[:media_tag] = params[:media_tag] if params[:media_tag].present?
      sql_p[:media_tag1] = params[:media_tag1] if params[:media_tag1].present?
      sql_p[:media_name] = params[:media_name] if params[:media_name].present?
      sql_p[:ad_user_name] = params[:ad_user_name] if params[:ad_user_name].present?
      sql_p[:landing_page_name] = params[:landing_page_name] if params[:landing_page_name].present?

      ransack_p = {}
      ransack_p[:eventkey_cont] = params[:eventkey] if params[:eventkey].present?
      ransack_p[:customer_type_cont] = params[:customer_type] if params[:customer_type].present?
      ransack_p[:customer_lv_cont] = params[:customer_lv] if params[:customer_lv].present?
      ransack_p[:city_name_cont] = params[:city_name] if params[:city_name].present?
      ransack_p[:city_lv_cont] = params[:city_lv] if params[:city_lv].present?
      ad_list = AdInfo.ransack(ransack_p).result(distinct:true).where(sql_p).where.not(status:10)

      new_ad_list = []
      ad_list.page(params[:page]).per(params[:per]).each{ |ad|
        # 查询
        event_key_info = RestClient::Request.execute(
          method:  "get",
          url:     "#{ENV["crm_host"]}api/channels/conversion_data",
          payload: "event_key=#{ad.eventkey}",
          headers: { "authorization": ENV["crm_authorization"]})
        event_key_info_code = JSON.parse(event_key_info).fetch("code", nil).to_i

        if event_key_info_code == 200
          # 设置信息
          event_key_data = JSON.parse(event_key_info).fetch("data", {});
          new_ad_list << ad.attributes.dup.merge(event_key_data)
        else
          # 新建
          res_event_key = RestClient::Request.execute(
            method:  "post",
            url:     "#{ENV["crm_host"]}api/channels/generate_tracking",
            payload: {
              :event_key     => ad.eventkey,
              :utm_source    => ad.media_name,
              :utm_medium    => ad.media_tag,
              :utm_campaign  => ad.register_type,
              :grade         => ad.customer_lv
            },
            headers: { "authorization": ENV["crm_authorization"]})
          res_event_key_code = JSON.parse(res_event_key).fetch("code", nil).to_i
          # 查询
          event_key_info1 = RestClient::Request.execute(
            method:  "get",
            url:     "#{ENV["crm_host"]}api/channels/conversion_data",
            payload: "event_key=#{ad.eventkey}",
            headers: { "authorization": ENV["crm_authorization"]})
          event_key_info_code1 = JSON.parse(event_key_info1).fetch("code", nil).to_i
          # 设置信息
          event_key_data1 = JSON.parse(event_key_info1).fetch("data", {});
          new_ad_list << ad.attributes.dup.merge(event_key_data1)
        end
      }
      render_json ad_list: new_ad_list, count: ad_list.count
    end

    get 'ad/select' do
      res = {}
      res[:activity_name] = AdInfo.pluck(:activity_name).uniq.reject { |e| e.to_s.empty?}
      res[:product] = AdInfo.pluck(:product).uniq.reject { |e| e.to_s.empty?}
      res[:register_type] = AdInfo.pluck(:register_type).uniq.reject { |e| e.to_s.empty?}
      res[:customer_type] = AdInfo.pluck(:customer_type).uniq.reject { |e| e.to_s.empty?}
      res[:customer_lv] = AdInfo.pluck(:customer_lv).uniq.reject { |e| e.to_s.empty?}
      res[:ad_source_name] = AdInfo.pluck(:ad_source_name).uniq.reject { |e| e.to_s.empty?}
      # res[:ad_source_url] = AdInfo.pluck(:ad_source_url).uniq.reject { |e| e.to_s.empty?}
      res[:landing_page_name] = AdInfo.pluck(:landing_page_name).uniq.reject { |e| e.to_s.empty?}
      res[:media] = AdInfo.pluck(:media_tag,:media_tag1,:media_name,:ad_user_name).uniq.reject { |e| e.to_s.empty?}
      render_json res
    end

    post 'ad/delete' do
      AdInfo.find_by(id:params[:id]).update(status:10)
      render_json
    end

    desc 'excel json格式数据导入'
    post 'ad/upload_excel_by_json' do
      p params
      list = params[:list]
      ActiveRecord::Base.transaction do 
        list.map{|val|
          val[:status] = 1
          AdInfo.create(val)
        }
      end
      list.each{|ad|
        res_event_key = RestClient::Request.execute(
          method:  "post", 
          url:     "#{ENV["crm_host"]}api/channels/generate_tracking",
          payload: {
            :event_key     => ad[:eventkey],
            :utm_source    => ad[:media_name],
            :utm_medium    => ad[:media_tag],
            :utm_campaign  => ad[:register_type],
            :grade         => ad[:customer_lv]
          },
          headers: { "authorization": ENV["crm_authorization"]})
      }
      render_json
    end

    desc 'excel 二进制格式文件数据导入'
    params do
      optional :file, type: Rack::Multipart::UploadedFile
    end
    post 'ad/upload_excel' do
      list = []
      path = params[:file][:tempfile].path
      spreadsheet = Roo::Spreadsheet.open(path) rescue Roo::Excel.new(path)
      header = spreadsheet.row(1)
        (2..spreadsheet.last_row).each{|i|
          row         = Hash[[header, spreadsheet.row(i)].transpose]
          list << {
            eventkey: row["eventkey"].to_s.squish,
            media_tag: row["媒体大类"].to_s.squish,
            media_tag1: row["媒体小类"].to_s.squish,
            media_name: row["媒体名称"].to_s.squish,
            ad_user_name: row["广告账户"].to_s.squish,
            ad_plan: row["广告计划"].to_s.squish,
            ad_unit: row["广告单元"].to_s.squish,
            key_word: row["关键字"].to_s.squish,
            ad_agent: row["广告代理商"].to_s.squish,
            city_lv: row["城市分级"].to_s.squish,
            city_name: row["城市名称"].to_s.squish,
            activity_name: row["活动名称"].to_s.squish,
            product: row["产品名称"].to_s.squish,
            register_type: row["报名方式"].to_s.squish,
            customer_lv: row["客户等级"].to_s.squish,
            customer_type: row["客户画像"].to_s.squish,
            ad_source_name: row["广告素材"].to_s.squish,
            landing_page_url: row["着陆页url"].to_s.squish,
            landing_page_name: row["着陆页名字"].to_s.squish,
            remark: row["备注"].to_s.squish,
            cost: row["花费"].to_i,
            status: 1
          }
        }
        
      ActiveRecord::Base.transaction do 
        list.map{|val|
          AdInfo.create(val)
        }
      end

      list.each{|ad|
        res_event_key = RestClient::Request.execute(
          method:  "post", 
          url:     "#{ENV["crm_host"]}api/channels/generate_tracking",
          payload: {
            :event_key     => ad[:eventkey],
            :utm_source    => ad[:media_name],
            :utm_medium    => ad[:media_tag],
            :utm_campaign  => ad[:register_type],
            :grade         => ad[:customer_lv]
          },
          headers: { "authorization": ENV["crm_authorization"]})
      }
      render_json
    end

    desc '导出需要的excel文件json'
    post 'ad/download_excel' do
      ad_list = AdInfo.where.not(status:10)
      render_json ad_list: ad_list
    end

  end
end

